<template>
  <div class="articleList">
    <!-- 上拉加载 -->
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">

      <!-- 下拉刷新 -->
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <van-cell v-for="item in list" :key="item.art_id" :title="item.title">
          <template #label>
            <!-- 图片 -->
            <van-grid v-if="item.cover.images" :column-num="item.cover.images.length">
              <van-grid-item v-for="(img,index) in item.cover.images" :key="index">
                <van-image lazy-load :src="img" />
              </van-grid-item>
            </van-grid>

            <!-- 描叙信息 -->
            <div class="meta">
              <span>{{ item.aut_name }}</span>
              <span>{{ item.comm_count }}评论</span>
              <span>{{ item.pubdate | relative }}</span>
              <van-icon v-if="tokenInfo.token" name="cross" @click="close(item)" />
            </div>
          </template>
        </van-cell>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { reqGetArticles } from '@/api/article'
import { mapState } from 'vuex'

export default {
  name: 'ArticleList',

  props: {
    channel: {
      type: Object,
      required: true
    }
  },

  data() {
    return {
      timestamp: null,
      list: [],
      loading: false,
      finished: false,
      isLoading: false
    }
  },

  created() {
    this.$eventBus.$on('del-article', obj => {
      const { articleId, channelId } = obj
      if (channelId === this.channel.id) {
        this.list = this.list.filter(item => item.art_id !== articleId)
      }
    })
  },

  computed: {
    ...mapState('user', ['tokenInfo'])
  },

  methods: {
    // 上拉加载
    async onLoad() {
      // 初始时间处理
      if (!this.timestamp) {
        this.timestamp = +new Date()
      }

      // 发送请求获取数据
      const res = await reqGetArticles(this.channel.id, this.timestamp)

      // 更新时间戳以及渲染列表
      this.timestamp = res.data.pre_timestamp
      this.list = [...this.list, ...res.data.results]

      // 加载完成后隐藏加载栏
      this.loading = false

      // 数据全部获取后显示结束栏
      if (res.data.results.length === 0 || this.timestamp === null) {
        this.finished = true
      }
    },

    // 下拉刷新
    async onRefresh() {
      // 获取最新列表
      const res = await reqGetArticles(this.channel.id, +new Date())

      // 更新时间戳以及渲染列表
      this.timestamp = res.data.pre_timestamp
      this.list = res.data.results

      // 结束loading状态
      this.isLoading = false

      // 提示刷新结束
      this.$toast('刷新成功')
    },

    // 点击显示弹出层
    close(item) {
      this.$emit('show-more', item.art_id)
    }
  }
}
</script>

<style lang="scss" scoped>
.articleList {
  .meta {
    margin-top: 15px;
    width: 100%;
    span{
      margin-right: 10px;
    }
    .van-icon {
      float: right;
      margin-top: 4px;
    }
  }
}
</style>
